package com.java.base.exercise.current;

import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @Author RenPu
 * @Date 2023/3/14 15:59
 * @Version 1.0
 * @Description: 基于AQS实现自定义的Semaphore
 **/
public class RenPuSemaphore {

    private Sync sync;

    public RenPuSemaphore(int permits) {
        sync=new Sync(permits);
    }

    public void acquire(){
        sync.acquireShared(1);
    }

    public void release(){
        sync.releaseShared(1);
    }

    class Sync extends AbstractQueuedSynchronizer{

        private int permits;

        public Sync(int permits) {
            this.permits = permits;
        }

        //由于Semaphore，是以一种共享锁的机制，所以选择重写Shared的方法
        @Override
        protected int tryAcquireShared(int i) {
            int state = getState();
            int nextInt=state+i;
            if(nextInt<=permits){
                if(compareAndSetState(state,nextInt)) return 1;
            }
            return -1;
        }

        @Override
        protected boolean tryReleaseShared(int i) {
            int state = getState();
            int nextInt=state-i;
            if(nextInt<=permits){
                compareAndSetState(state,nextInt);
                return true;
            }
            return false;

        }
    }


    public static void main(String[] args) {

//        Semaphore semaphore = new Semaphore(8);

        RenPuSemaphore semaphore = new RenPuSemaphore(8);

        for (int i = 0; i <20 ; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println("获取到信号量，开始执行。。。。。。");
                    Thread.sleep(5000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("方法执行完毕。。。。。。。。。");
                semaphore.release();
            }).start();

        }
    }





}
